package com.lishem.carl._02linkedlist;

import com.lishem.common.ListNode;

/**
 * https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
 * <p>
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * <p>
 * 示例 1：
 * <p>
 * 输入：head = [1,2,3,4,5], n = 2
 * <p>
 * 输出：[1,2,3,5]
 * <p>
 * 示例 2：
 * <p>
 * 输入：head = [1], n = 1
 * <p>
 * 输出：[]
 * <p>
 * 示例 3：
 * <p>
 * 输入：head = [1,2], n = 1
 * <p>
 * 输出：[1]
 */
public class _5LetCode19_删除链表的倒数第N个节点 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode addHead = new ListNode();
        addHead.next = head;
        ListNode slow = addHead;
        ListNode fast = addHead;
        while (n-- > 0) {
            fast = fast.next;
        }
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return addHead.next;
    }

    public static void main(String[] args) {
        _5LetCode19_删除链表的倒数第N个节点 sol = new _5LetCode19_删除链表的倒数第N个节点();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode.printListNode(head);
        ListNode.printListNode(sol.removeNthFromEnd(head, 2));
    }
}
